package com.lam.framework.config;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.DispatcherType;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import com.lam.common.utils.StringUtils;
import com.lam.framework.filter.HttpServletFilter;
import com.lam.framework.filter.LogMDCFilter;
import com.lam.framework.filter.XssFilter;

/**
 * Filter配置
 *
 * @author lam
 */
@Configuration
public class FilterConfig {
	
	@Value("${xss.enabled}")
	private String enabled;

	@Value("${xss.excludes}")
	private String excludes;

	@Value("${xss.urlPatterns}")
	private String urlPatterns;
	
	/**
	 * 跨域配置
	 */
	@Bean
	public CorsFilter corsFilter() {
		UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
		CorsConfiguration config = new CorsConfiguration();
		config.setAllowCredentials(true);
		// 设置访问源地址
		config.addAllowedOrigin("*");
		// 设置访问源请求头
		config.addAllowedHeader("*");
		// 设置访问源请求方法
		config.addAllowedMethod("*");
		// 对接口配置跨域设置
		source.registerCorsConfiguration("/**", config);
		return new CorsFilter(source);
	}
	
	@Bean
	public FilterRegistrationBean<XssFilter> xssFilterRegistration() {
		FilterRegistrationBean<XssFilter> registration = new FilterRegistrationBean<>();
		registration.setDispatcherTypes(DispatcherType.REQUEST);
		registration.setFilter(new XssFilter());
		registration.addUrlPatterns(StringUtils.split(urlPatterns, ","));
		registration.setName("xssFilter");
		registration.setOrder(FilterRegistrationBean.HIGHEST_PRECEDENCE);
		Map<String, String> initParameters = new HashMap<>();
		initParameters.put("excludes", excludes);
		initParameters.put("enabled", enabled);
		registration.setInitParameters(initParameters);
		return registration;
	}
	
	@Bean
	public FilterRegistrationBean<HttpServletFilter> someFilterRegistration() {
		FilterRegistrationBean<HttpServletFilter> registration = new FilterRegistrationBean<>();
		registration.setFilter(new HttpServletFilter());
		registration.addUrlPatterns("/*");
		registration.setName("HttpServletFilter");
		registration.setOrder(FilterRegistrationBean.HIGHEST_PRECEDENCE + 1);
		return registration;
	}
	
	@Bean
    public FilterRegistrationBean<LogMDCFilter> logFilterRegistration() {
        FilterRegistrationBean<LogMDCFilter> registration = new FilterRegistrationBean<>();
        registration.setFilter(new LogMDCFilter());
        registration.addUrlPatterns("/*");
        registration.setName("logMDCFilter");
        registration.setOrder(FilterRegistrationBean.HIGHEST_PRECEDENCE + 2);
        return registration;
    }
	
}
